package cn.tjad.tjad2.module.design.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qiandian.android.base.activity.BaseActivity;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.widget.TJADTTitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.DesignDetail;
import cn.tjad.tjad2.data.bean.MultiItemBean;
import cn.tjad.tjad2.module.design.adapter.DesignDetailAdapter;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.DocumentHelper;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.module.design.designDetail.DesignDetailTopView;
import cn.tjad.tjad2.module.design.designDetail.DesignHandleView;
import io.reactivex.Observable;

@Route(path = PageId.DESIGN_DETAIL)
public class DesignDetailActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    private int designId;
    private DesignDetailAdapter designDetailAdapter;
    private DesignDetailTopView topView;
    private DesignHandleView handleView;

    private final List<MultiItemBean> listData = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_recylerview);
        swipeRefreshLayout.setOnRefreshListener(this);
        designId = getIntent().getIntExtra(Keys.DESIGN_ID, -1);
        if (designId == -1) {
            Tools.showToast("没有有效的designId");
            finish();
            return;
        }
        topView = new DesignDetailTopView(this);
        handleView = new DesignHandleView(this);
        handleView.setCompositeDisposable(compositeDisposable);
        handleView.setEventHandler(handler);
        listData.add(new MultiItemBean(DesignDetailAdapter.ITEM_TYPE_TOP, null));
        designDetailAdapter = new DesignDetailAdapter(listData);
        designDetailAdapter.setTopView(topView);
        designDetailAdapter.setHandleView(handleView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(designDetailAdapter);
        requestDesignDetail();
    }

    @Override
    public void onTitleClick(int which) {
        super.onTitleClick(which);
        switch (which) {
            case TJADTTitleView.TITLE_RIGHT:
                //打开视口
                DesignDetail designDetail = (DesignDetail) getTitleView().getTag();
                if (designDetail == null || designDetail.document == null) {
                    return;
                }
                DocumentHelper.openModelFile(this, designDetail.document, "dqId", designDetail.id);
                break;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    requestDesignDetail();
                    recyclerView.smoothScrollToPosition(0);
                    break;
            }
        }
    };

    private void requestDesignDetail() {
        RetrofitManager.getInstance().getApiService().
                getDesignDetail(Tools.getProjectId(), designId)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<DesignDetail>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<DesignDetail> t) {
                        swipeRefreshLayout.setRefreshing(false);
                        if (t.result != null) {
                            updateUI(t.result);
                        }
                    }

                    @Override
                    public void onFailed(String message) {
                        Tools.showToast(message);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    private void updateUI(DesignDetail result) {
        if (result == null) {
            return;
        }
        if (result.document != null) {
            getTitleView().setRightImage(R.drawable.icon_view_entrance);
            getTitleView().showRight(true);
            getTitleView().setTag(result);
        } else {
            getTitleView().showRight(false);
            getTitleView().setTag(null);
        }
        topView.setData(result);
        handleView.setData(result);
        List<MultiItemBean> tempList = new ArrayList<>(listData);
        Observable.fromIterable(tempList)
                .filter(multiItemBean -> multiItemBean.getType() != DesignDetailAdapter.ITEM_TYPE_TOP)
                .subscribe(multiItemBean -> {
                    listData.remove(multiItemBean);
                });
        if (result.replies != null && result.replies.size() > 0) {
            Observable.fromIterable(result.replies)
                    .map(designReplyItem -> new MultiItemBean<>(DesignDetailAdapter.ITEM_TYPE_REPLY_ITEM, designReplyItem))
                    .doOnNext(designReplyItemMultiItemBean -> listData.add(designReplyItemMultiItemBean))
                    .subscribe();
        }
        if (result.consStatus == 2) { //完成
            listData.add(new MultiItemBean(DesignDetailAdapter.ITEM_TYPE_FINISH, result));
        } else {
            listData.add(new MultiItemBean(DesignDetailAdapter.ITEM_TYPE_HANDLE, result));
        }
        designDetailAdapter.notifyDataSetChanged();
    }

    /**
     * Called when a swipe gesture triggers a refresh.
     */
    @Override
    public void onRefresh() {
        requestDesignDetail();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        handleView.onActivityResult(requestCode, resultCode, data);
    }
}
